package com.xncoding.elasticsearch.config;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.*;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.springframework.stereotype.Component;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

//@Component
public class EsClient {
    private static final String INDEX_TYPE = "doc";
    private static final String HOST = "127.0.0.1";
    private RestClient lowClient;
    private RestHighLevelClient highClient;

    public EsClient() {
        lowClient = RestClient
                .builder(new HttpHost(HOST, 9200, "http"))
                .build();
        highClient = new RestHighLevelClient(RestClient.builder(
                new HttpHost(HOST, 9200, "http")));
    }

    public String saveIndex(String indexName, String jsonData) {
        try {
            IndexRequest request = new IndexRequest(indexName, INDEX_TYPE);
            request.source(jsonData, XContentType.JSON);
            IndexResponse indexResponse = highClient.index(request, RequestOptions.DEFAULT);
            System.out.println(String.format("存储es------>indexName:%s,status:%s,thread:%s", indexName, indexResponse.status(), Thread.currentThread()));
            return indexResponse.status().toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
    public QueryBuilder buildQueryBuilder(String keyword) {
        QueryBuilder totalBuilder;
        String[] andStr = keyword.split(",");
        String[] orStr = keyword.split(";");
        if (andStr.length > 1) {
            QueryStringQueryBuilder queryStringQueryBuilder;
            totalBuilder = QueryBuilders.boolQuery();
            for (String s : andStr) {
                queryStringQueryBuilder = QueryBuilders.queryStringQuery(s).defaultOperator(Operator.AND);
                ((BoolQueryBuilder) totalBuilder).filter(queryStringQueryBuilder);
            }
        } else if (orStr.length > 1) {
            QueryStringQueryBuilder queryStringQueryBuilder;
            totalBuilder = QueryBuilders.boolQuery();
            for (String s : orStr) {
                queryStringQueryBuilder = QueryBuilders.queryStringQuery(s).defaultOperator(Operator.AND);
                ((BoolQueryBuilder) totalBuilder).should(queryStringQueryBuilder);
            }
        } else {
            totalBuilder = QueryBuilders.queryStringQuery(keyword).defaultOperator(Operator.AND);
        }
        return totalBuilder;
    }

    public String querySql(String sql) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("query", "select * from chinese where a=987");
        HttpEntity httpEntity = new NStringEntity(jsonObject.toJSONString(), ContentType.APPLICATION_JSON);
        Request request = new Request("POST", "/_xpack/sql?format=txt");
        request.setEntity(httpEntity);
        try {
            Response response = lowClient.performRequest(request);
            String str = getInputStream(response.getEntity().getContent());
            return str;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    String getInputStream(InputStream inputStream) {
        BufferedInputStream bis = new BufferedInputStream(inputStream);
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        int result;
        try {
            result = bis.read();
            while (result != -1) {
                buf.write((byte) result);
                result = bis.read();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return buf.toString();
    }
}


